﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.Enums;
using BCCommon.PaymentEnums;
using BCEntity.Common.SystemFinanceFlowRecord;
using Dapper;

namespace BCData.Common.SystemFinanceFlowRecord
{
    public class SystemFinanceFlowRecordData : ISystemFinanceFlowRecordData
    {
        private const string QUERY = @"SELECT SystemFinanceFlowRecordId,OrderNo,UserId,UserName,FlowDirection,Amount,Balance,Channel,Remark,FlowType,CreateTime
					                    FROM SystemFinanceFlowRecord";

        private readonly IDatabaseContext databaseContext;

        public SystemFinanceFlowRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        public async Task<SystemFinanceFlowRecordEntity> Append(SystemFinanceFlowRecordEntity systemFinanceFlowRecordEntity)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("POrderNo", systemFinanceFlowRecordEntity.OrderNo, DbType.AnsiString, ParameterDirection.Input, size: 50);
            parameters.Add("PUserId", systemFinanceFlowRecordEntity.UserId, DbType.Int64, ParameterDirection.Input, size: 20);
            parameters.Add("PUserName", systemFinanceFlowRecordEntity.UserName, DbType.AnsiString, ParameterDirection.Input, size: 20);
            parameters.Add("PFlowDirection", systemFinanceFlowRecordEntity.FlowDirection.ToString(), DbType.AnsiString, ParameterDirection.Input);
            parameters.Add("PAmount", systemFinanceFlowRecordEntity.Amount, DbType.Decimal, ParameterDirection.Input);
            parameters.Add("PChannel", systemFinanceFlowRecordEntity.Channel.ToString(), DbType.AnsiString, ParameterDirection.Input);
            parameters.Add("PRemark", systemFinanceFlowRecordEntity.Remark, DbType.AnsiString, ParameterDirection.Input, size: 400);
            parameters.Add("PFlowType", systemFinanceFlowRecordEntity.FlowType.ToString(), DbType.AnsiString, ParameterDirection.Input);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SystemFinanceFlowRecordEntity>("SystemFinanceFlowAppendProcedure", parameters, databaseContext.Transaction, null, CommandType.StoredProcedure);
        }

        public async Task<(IEnumerable<SystemFinanceFlowRecordEntity>, int)> Query(string orderNo, long? userId, SourceFlowDirectionType? flowDirectionType, PaymentChannelType? payChannelType, FlowType? flowType, DateTime? start, DateTime? end, bool? ascending, int pageIndex = 1, int pageSize = 10)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                wheres.Add("OrderNo=?OrderNo");
                parameters.Add("?OrderNo", orderNo, DbType.AnsiString, size: 50);
            }
            if (userId.HasValue)
            {
                wheres.Add("UserId=?UserId");
                parameters.Add("?UserId", userId, DbType.Int64);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }
            if (payChannelType.HasValue)
            {
                wheres.Add("Channel=?Channel");
                parameters.Add("?Channel", payChannelType.Value.ToString(), DbType.Int64);
            }
            if (flowType.HasValue)
            {
                wheres.Add("FlowType=?FlowType");
                parameters.Add("?FlowType", flowType.Value.ToString(), DbType.Int64);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime {4} LIMIT {2},{3};
                               SELECT Count(1) FROM SystemFinanceFlowRecord
                               {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            return await this.databaseContext.Slave.QueryMultipleAsync<SystemFinanceFlowRecordEntity, int>(sql, parameters);
        }

        public async Task<(IEnumerable<SystemFinanceFlowRecordExtendEntity>, int)> GetAll(string orderNo, long? userId, SourceFlowDirectionType? flowDirectionType, PaymentChannelType? payChannelType, FlowType? flowType, DateTime? start, DateTime? end, bool? ascending, int pageIndex = 1, int pageSize = 10)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                wheres.Add("OrderNo=?OrderNo");
                parameters.Add("?OrderNo", orderNo, DbType.AnsiString, size: 50);
            }
            if (userId.HasValue)
            {
                wheres.Add("UserId=?UserId");
                parameters.Add("?UserId", userId, DbType.Int64);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }
            if (payChannelType.HasValue)
            {
                wheres.Add("Channel=?Channel");
                parameters.Add("?Channel", payChannelType.Value.ToString());
            }
            if (flowType.HasValue)
            {
                wheres.Add("FlowType=?FlowType");
                parameters.Add("?FlowType", flowType.Value.ToString());
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime {4} LIMIT {2},{3};
                               SELECT Count(1) FROM SystemFinanceFlowRecord
                               {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            return await this.databaseContext.Slave.QueryMultipleAsync<SystemFinanceFlowRecordExtendEntity, int>(sql, parameters);
        }

        public async Task<IEnumerable<SystemFinanceFlowRecordEntity>> GetEntities(string orderNo, SourceFlowDirectionType? flowDirectionType)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                wheres.Add("OrderNo=?OrderNo");
                parameters.Add("?OrderNo", orderNo, DbType.AnsiString, size: 50);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }

            string sql = string.Format(@"{0} {1};", QUERY, wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "");
            return await this.databaseContext.Slave.QueryAsync<SystemFinanceFlowRecordEntity>(sql, parameters);
        }

        public async Task<SystemFinanceFlowRecordEntity> GetLatRecordAsync()
        {
            string sql = string.Format("{0} ORDER BY SystemFinanceFlowRecordId DESC LIMIT 1", QUERY);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SystemFinanceFlowRecordEntity>(sql);
        }

        public async Task<SystemFinanceFlowRecordEntity> AppendTran(SystemFinanceFlowRecordEntity systemFinanceFlowRecordEntity)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("POrderNo", systemFinanceFlowRecordEntity.OrderNo, DbType.AnsiString, ParameterDirection.Input, size: 50);
            parameters.Add("PUserId", systemFinanceFlowRecordEntity.UserId, DbType.Int64, ParameterDirection.Input, size: 20);
            parameters.Add("PUserName", systemFinanceFlowRecordEntity.UserName, DbType.AnsiString, ParameterDirection.Input, size: 20);
            parameters.Add("PFlowDirection", systemFinanceFlowRecordEntity.FlowDirection.ToString(), DbType.AnsiString, ParameterDirection.Input);
            parameters.Add("PAmount", systemFinanceFlowRecordEntity.Amount, DbType.Decimal, ParameterDirection.Input);
            parameters.Add("PChannel", systemFinanceFlowRecordEntity.Channel.ToString(), DbType.AnsiString, ParameterDirection.Input);
            parameters.Add("PRemark", systemFinanceFlowRecordEntity.Remark, DbType.AnsiString, ParameterDirection.Input, size: 400);
            parameters.Add("PFlowType", systemFinanceFlowRecordEntity.FlowType.ToString(), DbType.AnsiString, ParameterDirection.Input);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SystemFinanceFlowRecordEntity>("SystemFinanceFlowAppendProcedure", parameters, databaseContext.Transaction, null, CommandType.StoredProcedure);
        }
    }
}